package com.cqndt.disaster.device.common.shrio;

import java.io.Serializable;
import org.apache.shiro.session.Session;
import com.cqndt.disaster.device.util.Keys;
import org.springframework.stereotype.Component;
import com.cqndt.disaster.device.common.util.MapKeys;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;

/**
 * @author lgb
 * @date 2020-8-31
 * @说明 shiro session service
 **/
@Component
public class RedisShiroSessionDAO extends EnterpriseCacheSessionDAO {
	
    //创建session
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = super.doCreate(session);
        final String key = "sessionid:"+sessionId.toString();
        setShiroSession(key, session);
        return sessionId;
    }

    //获取session
    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = super.doReadSession(sessionId);
        if(session == null){
            final String key = "sessionid:"+sessionId.toString();
            session = getShiroSession(key);
        }
        return session;
    }

    //更新session
    @Override
    protected void doUpdate(Session session) {
        super.doUpdate(session);
        final String key = "sessionid:"+session.getId().toString();
        setShiroSession(key, session);
    }

    //删除session
    @Override
    protected void doDelete(Session session) {
        super.doDelete(session);
        final String key = "sessionid:"+session.getId().toString();
        MapKeys.getKeyMap().remove(key);
    }

    private Session getShiroSession(String key) {
        return (Session)MapKeys.getKeyMap().get(key).getObj();
    }

    private void setShiroSession(String key,Session session){
    	Keys keys = new Keys(System.currentTimeMillis(),session);
    	MapKeys.getKeyMap().put(key,keys);
    }

}